package com.eques.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;

import com.eques.icvss.utils.ELog;

import java.lang.reflect.Method;

/**
 * Created on 2017/7/27.
 */
public class ScreenUtils {
    private static final String TAG = "ScreenUtils";

    private ScreenUtils() {
        throw new AssertionError();
    }

    // 锁屏标记（亮屏、解锁、允许弹框）
    public static void unLockScreen(Activity activity) {
        final Window win = activity.getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED // 使得应用程序窗口优先于锁屏界面
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD  // 解除锁屏，非加密锁屏，配合FLAG_SHOW_WHEN_LOCKED使用，就可以加密锁屏状态下，显示窗口
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON   // 窗口可见时，保持设备常开，并保持亮度不变
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON      // 窗口一旦显示出来，系统将点亮屏幕
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    }

    /**
     * 解锁亮屏
     *
     * @param context
     */
    @SuppressLint({"InvalidWakeLockTag", "ObsoleteSdkInt"})
    public static void unlockScreen(Context context, boolean isNotifyMsg) {
        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        ELog.d(TAG, " unlockScreen() pm.isScreenOn(): ", pm.isScreenOn());
        if (!pm.isScreenOn()) {
            //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
            //点亮屏幕
            wl.acquire(1000);
            //释放
            wl.release();

            // 当超过timeOut之后系统自动释放WakeLock
            /*wl.acquire(1000);
            ELog.d(TAG, " unlockScreen() bright... ");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                ELog.d(TAG, " unlockScreen() 14 bright... ");
                wl.release();
            }*/
        } else {
            ELog.d(TAG, " unlockScreen() notify null... ");
        }
        if (!isNotifyMsg) {
            ELog.d(TAG, " unlockScreen() non notify... ");
            // 屏幕解锁
            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            KeyguardLock kl = null;
            if (km != null) {
                kl = km.newKeyguardLock("unLock");
            }
            if (kl != null) {
                kl.disableKeyguard();//解锁
            }
            ELog.d(TAG, " unlockScreen() unLock... ");
        }
    }

    /**
     * 获取是否有虚拟按键
     * 通过判断是否有物理返回键反向判断是否有虚拟按键
     *
     * @param context
     * @return
     */
    private static boolean isNavigationBarShow(Activity activity, Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                //不存在虚拟按键
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                //存在虚拟按键
                //hasNavigationBar = true;
                hasNavigationBar = isNavigationBarShow(activity);
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    /**
     * 虚拟操作拦（home等）是否显示
     */
    public static boolean isNavigationBarShow(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(activity).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            return !menu && !back;
        }
    }

    /**
     * 判断是否锁屏状态
     *
     * @param context
     * @return
     */
    public final static boolean isScreenLocked(Context context) {
        if (null != context) {
            KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(
                    Context.KEYGUARD_SERVICE);
            //* 如果flag为true，表示有两种状态：a、屏幕是黑的 b、目前正处于解锁状态 。
            //* 如果flag为false，表示目前未锁屏
            //* 关闭屏幕不等于锁屏
            return mKeyguardManager.inKeyguardRestrictedInputMode();
        }

        return false;
    }

    /**
     * 为true，则表示屏幕“亮”了，否则屏幕“暗”了。
     *
     * @param context
     * @return
     */
    public final static boolean isScreenOn(Context context) {
        ELog.d(TAG, " isScreenOn() start... ");
        if (null != context) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (pm != null) {
                // 判断屏幕是否亮着,在API20被弃用,推荐isInteractive()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                    ELog.d(TAG, " isScreenOn() pm.isInteractive(): ", pm.isInteractive());
                    return pm.isInteractive();
                }
                ELog.d(TAG, " isScreenOn() pm.isScreenOn(): ", pm.isScreenOn());
                return pm.isScreenOn();
            } else {
                ELog.d(TAG, " isScreenOn() pm is null... ");
            }
        } else {
            ELog.d(TAG, " isScreenOn() context is null... ");
        }
        return false;
    }

    /**
     * dp单位转成px
     *
     * @param context context
     * @param dp      dp值
     * @return px值
     */
    public static int dp2px(Context context, int dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density);
    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        // 一般是25dp
        int height = dp2px(context, 25);
        ELog.i(TAG, "common statusBar height:" + height);
        //获取status_bar_height资源的ID
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
            ELog.i(TAG, "real statusBar height:" + height);
        }
        ELog.i(TAG, "finally statusBar height:" + height);
        return height;
    }

    /**
     * 获取虚拟操作拦（home等）高度
     */
    public static int getNavigationBarHeight(Activity activity) {
        if (!isNavigationBarShow(activity))
            return 0;
        int height = 0;
        Resources resources = activity.getResources();
        //获取NavigationBar的高度
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0)
            height = resources.getDimensionPixelSize(resourceId);
        ELog.i(TAG, "NavigationBar的高度:" + height);
        return height;
    }

    /**
     * 获取虚拟按键的高度
     *
     * @param context
     * @return
     */
    public static int getNavigationBarHeight(Activity activity, Context context) {
        int result = 0;
        if (isNavigationBarShow(activity, context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 屏幕背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;

        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 设置状态栏为全透明
     * 通过设置theme的方式无法达到全透明效果
     *
     * @param activity
     */
    @TargetApi(19)
    public static void transparencyStatusBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0及其以上
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4及其以上
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}
